# 增强的API序列化器
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import (
    Asset, AssetCategory, Department, Location, Supplier, Contract,
    MaintenanceRecord, AssetBorrow, Consumable, Warehouse, InventoryLog
)


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    
    class Meta:
        model = User
        fields = ['id', 'username', 'first_name', 'last_name', 'email']
        read_only_fields = ['id']


class AssetCategorySerializer(serializers.ModelSerializer):
    """资产类别序列化器"""
    
    asset_count = serializers.SerializerMethodField()
    
    class Meta:
        model = AssetCategory
        fields = ['id', 'name', 'description', 'asset_count']
        read_only_fields = ['id', 'asset_count']
    
    def get_asset_count(self, obj):
        """获取该类别下的资产数量"""
        return obj.asset_set.count()


class DepartmentSerializer(serializers.ModelSerializer):
    """部门序列化器"""
    
    manager = UserSerializer(read_only=True)
    asset_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Department
        fields = ['id', 'name', 'description', 'manager', 'asset_count']
        read_only_fields = ['id', 'asset_count']
    
    def get_asset_count(self, obj):
        """获取该部门的资产数量"""
        return obj.asset_set.count()


class LocationSerializer(serializers.ModelSerializer):
    """位置序列化器"""
    
    class Meta:
        model = Location
        fields = ['id', 'name', 'description', 'address']
        read_only_fields = ['id']


class SupplierSerializer(serializers.ModelSerializer):
    """供应商序列化器"""
    
    asset_count = serializers.SerializerMethodField()
    contract_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Supplier
        fields = [
            'id', 'name', 'contact_person', 'phone', 'email', 'address',
            'status', 'rating', 'asset_count', 'contract_count',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'asset_count', 'contract_count', 'created_at', 'updated_at']
    
    def get_asset_count(self, obj):
        """获取该供应商的资产数量"""
        return obj.asset_set.count()
    
    def get_contract_count(self, obj):
        """获取该供应商的合同数量"""
        return obj.contract_set.count()


class AssetListSerializer(serializers.ModelSerializer):
    """资产列表序列化器（简化版）"""
    
    category_name = serializers.CharField(source='category.name', read_only=True)
    department_name = serializers.CharField(source='department.name', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = Asset
        fields = [
            'id', 'name', 'asset_number', 'category_name', 'department_name',
            'status', 'status_display', 'purchase_price', 'purchase_date'
        ]
        read_only_fields = ['id', 'category_name', 'department_name', 'status_display']


class AssetDetailSerializer(serializers.ModelSerializer):
    """资产详情序列化器（完整版）"""
    
    category = AssetCategorySerializer(read_only=True)
    department = DepartmentSerializer(read_only=True)
    location = LocationSerializer(read_only=True)
    supplier = SupplierSerializer(read_only=True)
    
    # 关联数据
    maintenance_count = serializers.SerializerMethodField()
    borrow_count = serializers.SerializerMethodField()
    current_value = serializers.SerializerMethodField()
    
    class Meta:
        model = Asset
        fields = [
            'id', 'name', 'asset_number', 'description', 'category', 'department',
            'location', 'supplier', 'status', 'purchase_price', 'purchase_date',
            'warranty_end_date', 'specifications', 'maintenance_count',
            'borrow_count', 'current_value', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'maintenance_count', 'borrow_count', 'current_value',
            'created_at', 'updated_at'
        ]
    
    def get_maintenance_count(self, obj):
        """获取维修记录数量"""
        return obj.maintenancerecord_set.count()
    
    def get_borrow_count(self, obj):
        """获取借用记录数量"""
        return obj.assetborrow_set.count()
    
    def get_current_value(self, obj):
        """获取当前价值（考虑折旧）"""
        # 这里可以实现折旧计算逻辑
        return float(obj.purchase_price or 0)


class AssetCreateSerializer(serializers.ModelSerializer):
    """资产创建序列化器"""
    
    class Meta:
        model = Asset
        fields = [
            'name', 'asset_number', 'description', 'category', 'department',
            'location', 'supplier', 'status', 'purchase_price', 'purchase_date',
            'warranty_end_date', 'specifications'
        ]
    
    def validate_asset_number(self, value):
        """验证资产编号唯一性"""
        if Asset.objects.filter(asset_number=value).exists():
            raise serializers.ValidationError("资产编号已存在")
        return value
    
    def validate_purchase_price(self, value):
        """验证购买价格"""
        if value is not None and value < 0:
            raise serializers.ValidationError("购买价格不能为负数")
        return value


class MaintenanceRecordSerializer(serializers.ModelSerializer):
    """维修记录序列化器"""
    
    asset = AssetListSerializer(read_only=True)
    asset_id = serializers.IntegerField(write_only=True)
    assigned_to = UserSerializer(read_only=True)
    assigned_to_id = serializers.IntegerField(write_only=True, required=False)
    
    class Meta:
        model = MaintenanceRecord
        fields = [
            'id', 'asset', 'asset_id', 'maintenance_type', 'description',
            'status', 'priority', 'assigned_to', 'assigned_to_id',
            'estimated_cost', 'actual_cost', 'scheduled_date',
            'started_at', 'completed_at', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def validate_actual_cost(self, value):
        """验证实际成本"""
        if value is not None and value < 0:
            raise serializers.ValidationError("实际成本不能为负数")
        return value


class AssetBorrowSerializer(serializers.ModelSerializer):
    """资产借用序列化器"""
    
    asset = AssetListSerializer(read_only=True)
    asset_id = serializers.IntegerField(write_only=True)
    borrower = UserSerializer(read_only=True)
    approved_by = UserSerializer(read_only=True)
    
    class Meta:
        model = AssetBorrow
        fields = [
            'id', 'asset', 'asset_id', 'borrower', 'purpose', 'status',
            'borrow_date', 'expected_return_date', 'actual_return_date',
            'approved_by', 'approval_date', 'notes', 'created_at'
        ]
        read_only_fields = ['id', 'borrower', 'approved_by', 'approval_date', 'created_at']


class WarehouseSerializer(serializers.ModelSerializer):
    """仓库序列化器"""
    
    consumable_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Warehouse
        fields = ['id', 'name', 'description', 'address', 'consumable_count']
        read_only_fields = ['id', 'consumable_count']
    
    def get_consumable_count(self, obj):
        """获取该仓库的耗材种类数量"""
        return obj.consumable_set.count()


class ConsumableSerializer(serializers.ModelSerializer):
    """耗材序列化器"""
    
    warehouse = WarehouseSerializer(read_only=True)
    warehouse_id = serializers.IntegerField(write_only=True)
    stock_status = serializers.SerializerMethodField()
    total_value = serializers.SerializerMethodField()
    
    class Meta:
        model = Consumable
        fields = [
            'id', 'name', 'description', 'warehouse', 'warehouse_id',
            'quantity', 'min_quantity', 'unit', 'unit_price',
            'stock_status', 'total_value', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'stock_status', 'total_value', 'created_at', 'updated_at']
    
    def get_stock_status(self, obj):
        """获取库存状态"""
        if obj.quantity <= 0:
            return 'out_of_stock'
        elif obj.quantity <= obj.min_quantity:
            return 'low_stock'
        else:
            return 'normal'
    
    def get_total_value(self, obj):
        """获取总价值"""
        return float(obj.quantity * (obj.unit_price or 0))
    
    def validate_quantity(self, value):
        """验证数量"""
        if value < 0:
            raise serializers.ValidationError("数量不能为负数")
        return value
    
    def validate_min_quantity(self, value):
        """验证最小库存"""
        if value < 0:
            raise serializers.ValidationError("最小库存不能为负数")
        return value
    
    def validate_unit_price(self, value):
        """验证单价"""
        if value is not None and value < 0:
            raise serializers.ValidationError("单价不能为负数")
        return value


class InventoryLogSerializer(serializers.ModelSerializer):
    """库存记录序列化器"""
    
    consumable = ConsumableSerializer(read_only=True)
    operator = UserSerializer(read_only=True)
    
    class Meta:
        model = InventoryLog
        fields = [
            'id', 'consumable', 'operation_type', 'quantity_change',
            'quantity_before', 'quantity_after', 'unit_price',
            'total_amount', 'reason', 'operator', 'created_at'
        ]
        read_only_fields = ['id', 'operator', 'created_at']


class ContractSerializer(serializers.ModelSerializer):
    """合同序列化器"""
    
    supplier = SupplierSerializer(read_only=True)
    supplier_id = serializers.IntegerField(write_only=True)
    created_by = UserSerializer(read_only=True)
    
    # 合同状态
    is_active = serializers.SerializerMethodField()
    days_until_expiry = serializers.SerializerMethodField()
    
    class Meta:
        model = Contract
        fields = [
            'id', 'contract_number', 'title', 'supplier', 'supplier_id',
            'contract_amount', 'start_date', 'end_date', 'status',
            'description', 'is_active', 'days_until_expiry',
            'created_by', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'is_active', 'days_until_expiry', 'created_by',
            'created_at', 'updated_at'
        ]
    
    def get_is_active(self, obj):
        """判断合同是否有效"""
        from django.utils import timezone
        today = timezone.now().date()
        return obj.start_date <= today <= obj.end_date if obj.start_date and obj.end_date else False
    
    def get_days_until_expiry(self, obj):
        """获取距离到期的天数"""
        if not obj.end_date:
            return None
        
        from django.utils import timezone
        today = timezone.now().date()
        delta = obj.end_date - today
        return delta.days
    
    def validate_contract_number(self, value):
        """验证合同编号唯一性"""
        if Contract.objects.filter(contract_number=value).exists():
            raise serializers.ValidationError("合同编号已存在")
        return value
    
    def validate(self, data):
        """验证合同数据"""
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        
        if start_date and end_date and start_date > end_date:
            raise serializers.ValidationError("开始日期不能晚于结束日期")
        
        contract_amount = data.get('contract_amount')
        if contract_amount is not None and contract_amount < 0:
            raise serializers.ValidationError("合同金额不能为负数")
        
        return data


# 统计数据序列化器
class AssetStatisticsSerializer(serializers.Serializer):
    """资产统计序列化器"""
    
    total_count = serializers.IntegerField()
    status_counts = serializers.DictField()
    category_counts = serializers.DictField()
    department_counts = serializers.DictField()
    total_value = serializers.DecimalField(max_digits=15, decimal_places=2)
    average_value = serializers.DecimalField(max_digits=15, decimal_places=2)


class MaintenanceStatisticsSerializer(serializers.Serializer):
    """维修统计序列化器"""
    
    total_count = serializers.IntegerField()
    status_counts = serializers.DictField()
    type_counts = serializers.DictField()
    total_cost = serializers.DecimalField(max_digits=15, decimal_places=2)
    average_cost = serializers.DecimalField(max_digits=15, decimal_places=2)
    monthly_trends = serializers.ListField()


class InventoryStatisticsSerializer(serializers.Serializer):
    """库存统计序列化器"""
    
    total_items = serializers.IntegerField()
    low_stock_items = serializers.IntegerField()
    out_of_stock_items = serializers.IntegerField()
    total_value = serializers.DecimalField(max_digits=15, decimal_places=2)
    warehouse_distribution = serializers.DictField()